package com.ygqh.baby.controller.admin;

import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.model.AgentUserModel;
import com.ygqh.baby.po.YgAgent;
import com.ygqh.baby.po.YgAgentLevel;
import com.ygqh.baby.po.YgRechargeMemberRecord;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.*;
import com.ygqh.baby.utils.YgStringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Ss
 */
@Controller
@RequestMapping("/admin/agent")
public class AgentController extends BaseController<Object, java.lang.Long> {

	@Autowired
	private YgAgentService ygAgentService;
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private WxMpMessageService wxMpMessageService;
	@Autowired
	private YgAgentInviteRecordService ygAgentInviteRecordService;
	@Autowired
	private SmsService smsService;
	@Autowired
	private YgAgentLevelService ygAgentLevelService;
	@Autowired
	private YgRechargeMemberRecordService ygRechargeMemberRecordService;

	@RequestMapping("searchAgent")
	@ResponseBody
	public Map<String, Object> searchAgent(String nickName, QueryInfo queryInfo, String userName, Date startDate,
										   Date endDate,Date orderStartDate,Date orderEndDate, Long levelId) {
		ResultSet<AgentUserModel> result = ygAgentInviteRecordService.search(queryInfo, nickName, userName,
				startDate, endDate, orderStartDate, orderEndDate, levelId);
		return result.toDatatables(null);
	}

	@RequestMapping("updateCheckStatus")
	@ResponseBody
	public Message updateCheckStatus(Long id, CheckStatus checkStatus, String checkRemark, Long userId,
									 String userName, String openId) {
		ygAgentService.updateCheckStatus(id, checkStatus, checkRemark, getSession().getTrueName(),new Date());
		if(checkStatus.equals(CheckStatus.Pass)){
			YgUser ygUser=new YgUser();
			ygUser.setId(userId);
			ygUser.setUserType(UserType.UserAgent);
			ygUserService.updateUserInfo(ygUser);
		}
		wxMpMessageService.sendAgentAuditMsg(userName, openId, checkStatus, checkRemark);
		return SUCCESS_MESSAGE;
	}

	@RequestMapping("getAgent")
	@ResponseBody
	public YgAgent getAgent(Long id) {
		return ygAgentService.findAgentInfo(id);
	}
	
	@RequestMapping("createGroupHead")
	@ResponseBody
	public Message createGroupHead(Long userId) {
		return ygAgentService.saveGroupHead(userId, getSession().getTrueName());
	}

	@RequestMapping("cancelGroupHead")
	@ResponseBody
	public Message cancelGroupHead(Long userId, String userName, String openId) {
		Message message = ygAgentService.createCancelJob(userId, getSession().getTrueName(), UserType.Group);
		/*if (message.getType().equals(Message.Type.success)) {
			message = wxMpMessageService.cancelAgentAuditMsg(userName, openId,
					"您好，您的团长资格将在5天后取消，有疑问请联系客服。", "/channel/index.html?usertype=Group");
		}*/
		return message;
	}

	@RequestMapping("cancelUserAgent")
	@ResponseBody
	public Message cancelUserAgent(Long userId, String userName) {
		Message message = ygAgentService.createCancelJob(userId, getSession().getTrueName(), UserType.UserAgent);
		if (message.getType().equals(Message.Type.success)) {
			// 发送消息提醒
			try {
				if (YgStringUtils.isChinaPhoneLegal(userName)) {
					smsService.sendSms(userName, "您好，您的代理资格将在5天后取消，有疑问请联系壹果客服。");
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}
		return message;
	}

	@RequestMapping("deleteCancelAgent")
	@ResponseBody
	public Message deleteCancelAgent(Long userId) {
		return ygAgentService.deleteCancelOperation(userId, getSession().getTrueName());
	}

	@RequestMapping("generateInviteCode")
	@ResponseBody
	public Message generateInviteCode(Long userId) {
		return Message.success(ygAgentInviteRecordService.generateInviteCodeToUser(userId));
	}

	/**
	 * 邀请用户立即成为新代理
	 * @param userId
	 * @return
	 */
	@RequestMapping("rechargeUserAgentWithNoPay")
	@ResponseBody
	public Message rechargeUserAgentWithNoPay(@RequestParam Long userId) {
		return ygAgentInviteRecordService.rechargeUserAgentRightNow(userId, Boolean.TRUE);
	}

	@RequestMapping("searchUserAgentCount")
	@ResponseBody
	public Map<String, Object> searchUserAgentCount(QueryInfo queryInfo) {
		ResultSet<Map<String, Object>> result = ygAgentService.searchUserAgentReport(queryInfo);
		return result.toDatatables(null);
	}

	@RequestMapping("rechargeUserAgent")
	@ResponseBody
	public Message rechargeUserAgent(@RequestParam Long userId) {
		YgUser user = ygUserService.findById(userId);
		if (user == null) {
			return Message.error("该用户不存在", null);
		}
		if (UserType.UserAgent.equals(user.getUserType())) {
			return Message.error("该用户已经是代理会员", null);
		}
		ygAgentService.rechargeUserAgent(user, getSession().getTrueName(), Constant.YIJIADIAN_PLATFORM_NO);
		return Message.success(null);
	}

	/**
	 * 更新用户代理等级
	 *
	 * @param userId
	 * @param levelId
	 * @return
	 */
	@RequestMapping("updateLevelRate")
	@ResponseBody
	public Message updateLevelRate(Long userId, Long levelId) {
		YgAgent agent = ygAgentService.findValidByUserId(userId, UserType.UserAgent);
		if (agent == null) {
			return Message.error("该用户不是代理", null);
		}
		YgAgent record = new YgAgent();
		record.setId(agent.getId());
		record.setLevelId(levelId);
		record.setUpdateBy(getSession().getTrueName());
		record.setUpdateTime(new Date());
		return Message.success(ygAgentService.update(record));
	}

	@RequestMapping("agentPayInfo")
	@ResponseBody
	public Message agentPayInfo(Long userId) {
		ResultSet<YgRechargeMemberRecord> resultSet = ygRechargeMemberRecordService.
				searchRecordByUserId(userId, CodeType.RechargeAG);
		List<YgRechargeMemberRecord> result = resultSet.getResult();
		if (CollectionUtils.isEmpty(result) || result.get(0).getRefundTime() != null) {
			return Message.success(null);
		}
		return Message.success(result.get(0));
	}

	@RequestMapping("cancelRightNow")
	@ResponseBody
	public Message cancelRightNow(@RequestParam Long userId,
                                  @RequestParam(defaultValue = "UserAgent") UserType userType, String remark,
                                  BigDecimal refundPrice) {
		return ygAgentService.cancelUserAgent(userId, getSession().getTrueName(), userType, remark, refundPrice);
	}

	/**
	 * 代理等级列表
	 *
	 * @param queryInfo
	 * @param levelName
	 * @return
	 */
	@RequestMapping("searchAgentLevel")
	@ResponseBody
	public Map<String, Object> searchAgentLevel(QueryInfo queryInfo, String levelName) {
		ResultSet<YgAgentLevel> resultSet = ygAgentLevelService.search(queryInfo, levelName);
		return resultSet.toDatatables(null);
	}

	/**
	 * 编辑代理等级信息
	 *
	 * @param agentLevel
	 * @return
	 */
	@RequestMapping("editAgentLevel")
	@ResponseBody
	public Message editAgentLevel(YgAgentLevel agentLevel) {
		agentLevel.setUpdateBy(getSession().getTrueName());
		return ygAgentLevelService.edit(agentLevel);
	}

	/**
	 * 删除代理等级信息
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping("delAgentLevel")
	@ResponseBody
	public Message delAgentLevel(@RequestParam Long id) {
		List<YgAgent> agentList = ygAgentService.findByLevelId(id);
		if (CollectionUtils.isNotEmpty(agentList)) {
			return Message.error("删除失败，已有代理用户配置该等级", null);
		}
		return Message.success(ygAgentLevelService.deleteSoft(id, getSession().getTrueName()));
	}

}
